/**
 * example:
 * html:
 * <div ng-controller="NoSeatController">
 <input type="button" class="btn btn-primary btn-xs" value="切换场次" ng-click="changeEvent()">
 <select-no-seat id="aa" event-id="obj.eventId" max-ticket-num="200" ng-model="data">
 <input type="button" class="btn btn-primary btn-xs" value="无座下单" ng-click="ok()">
 </select-no-seat>
 </div>
 *
 * js:
 * controllerModule.controller("NoSeatController",['$scope',function($scope){
        $scope.data=[{goodsId: "305138542240206848",count:4},{goodsId:"305138565787029504",count:777}];
        //$scope.data=[];
        $scope.ok=function(){
            console.info($scope.data);
        };
        $scope.obj={"eventId":"305138514553606144"};

        $scope.changeEvent=function(){
            $scope.$broadcast('reload-aa',"289571204040364032");
        }
    }]);
 */
define(['common/js/service/pms-common-service-0.1'],
    function () {
        diretiveModule.directive('selectNoSeat', ['$rootScope', 'MaiDialog', 'PmsCommonService', function ($rootScope, MaiDialog, PmsCommonService) {
            return {
                restrict: 'AE',
                require: 'ngModel',
                scope: {
                    ngModel: '=',
                    eventId: '=',
                    eventName: '=',
                    saleChannel:'=',
                    maxTicketNum: "@",
                    id: '@',
                    onlyModel: '@',
                    containModelNum:"@",
                    afterChange: '&',
                    afterLoad:'&'
                },
                transclude: true,
                templateUrl: rootPath + '/common/js/html/selectNoSeat.html',

                compile: function (tElem, tAttrs) {
                    return {

                        post: function (scope, iElem, iAttrs) {
                            scope.allSelectNum = 0;
                            scope.allSelectPrice = 0;

                            //以下为方法定义
                            scope.loadSelectionData = function () {
                                //根据最新的条件获取数据

                                var params = {"eventId": scope.eventId};
                                if(scope.saleChannel){
                                    params.saleChannel=scope.saleChannel;
                                }
                                PmsCommonService.getPriceList4NoSeat(params).then(function (data) {
                                    scope.prices = data;
                                    if (scope.prices != null) {
                                        angular.forEach(scope.prices, function (price) {
                                            //档位下架
                                        	price.showPrice = decimalPoint(price.price);
                                            if(price.goodOperationState==1){
                                                price.isDisabled = true;
                                                return true;
                                            }
                                            if (scope.ngModel && scope.ngModel.length > 0) {
                                                angular.forEach(scope.ngModel, function (obj) {
                                                    if (price.superGoodIds == obj.goodsId) {
                                                        price.isSelect = true;
                                                        price.selectNum = obj.count;
                                                        scope.allSelectNum += price.selectNum;
                                                        scope.allSelectPrice = FloatAdd(scope.allSelectPrice, FloatMul(price.price, price.selectNum));
                                                        if (scope.containModelNum) {
                                                            price.marginCount += obj.count;
                                                        }
                                                        //如果只可从model里选择，库存数量是model里对应票档数量
                                                        if(scope.onlyModel){
                                                            price.marginCount=price.selectNum;
                                                        }
                                                    }
                                                });
                                            }
                                            //如果只选在model里票档,
                                            //
                                            // 并且当前票档不是model里的票档，则设置
                                            if (scope.onlyModel && !price.isSelect) {
                                                price.isDisabled = true;
                                            }
                                        });
                                        var priceInfo = scope.prices;
                                        scope.afterLoad({"priceInfo":priceInfo});
                                    }
                                    console.info(data)
                                });
                            };
                            /**
                             * 选中票档
                             */
                            scope.selectPrice = function (index) {
                                if(scope.prices[index].isDisabled){
                                    return;
                                }
                                if (scope.prices[index].marginCount > 0) {
                                    if (scope.prices[index].isSelect) {
                                        scope.prices[index].selectNum = 0;
                                        scope.prices[index].isSelect = false;
                                    } else {
//                                        if (scope.allSelectNum >= scope.maxTicketNum) {
//                                            // MaiDialog.error("单笔订单最多" + scope.maxTicketNum + "张票");
//                                            var msg = "单笔订单最多" + scope.maxTicketNum + "张票";
//                                            scope.showError(index, msg);
//                                            return false;
//                                        }
                                        scope.prices[index].selectNum = 1;
                                        scope.prices[index].isSelect = true;
                                    }
                                    scope.pricesChange();
                                    //改变之后的回调
                                    var priceInfo = scope.prices[index];
                                    scope.afterChange({
                                    	"priceInfo":priceInfo
                                    });
                                }
                            };
                            
                            /**
                             * 增加或者减少的购买数量  动态的变更金额
                             */
                            scope.pricesChange = function () {
                                var allSelectNum = 0;
                                var allSelectPrice = 0;
                                scope.ngModel.length = 0;
                                for (var i = 0; i < scope.prices.length; i++) {
                                    if (scope.prices[i].isSelect) {
                                        allSelectNum += parseInt(scope.prices[i].selectNum);
                                        allSelectPrice = FloatAdd(allSelectPrice, FloatMul(scope.prices[i].price, scope.prices[i].selectNum));
                                        var obj = new Object();
                                        obj.count = scope.prices[i].selectNum;
                                        obj.price = scope.prices[i].price;
                                        obj.goodsId = scope.prices[i].superGoodIds;
                                        scope.ngModel.push(obj);
                                    }

                                }
                                scope.allSelectNum = allSelectNum;
                                scope.allSelectPrice = decimalPoint(allSelectPrice);
                            };
                            scope.subNumber = function (index) {
                                scope.clearError(index);
                                if (scope.prices[index].selectNum - 1 != 0)
                                    scope.prices[index].selectNum--;

                                if (scope.prices[index].marginCount < (scope.prices[index].selectNum + 1)) {
                                    scope.prices[index].selectNum = scope.prices[index].marginCount;
                                    scope.pricesChange();
                                    var priceInfo = scope.prices[index];
                                    scope.afterChange({
                                    	"priceInfo":priceInfo
                                    });
                                    var msg = "余票不足！";
                                    scope.showError(index, msg);
                                    return;
                                }
                                scope.pricesChange();
                                var priceInfo = scope.prices[index];
                                scope.afterChange({
                                	"priceInfo":priceInfo
                                });
                            };
                            
                            /** 
                             * 无座 购买座位 addNumber
                             */
                            scope.addNumber = function (index) {
                                scope.clearError(index);
//                                if (scope.allSelectNum >= scope.maxTicketNum) {
//                                    var msg = "单笔订单最多" + scope.maxTicketNum + "张票";
//                                    scope.showError(index, msg);
//                                    return false;
//                                }

                                if (!scope.prices[index].selectNum || !/^[0-9]*$/.test(scope.prices[index].selectNum)) {
                                    scope.prices[index].selectNum = 0;
                                }
                                if (scope.prices[index].marginCount < (scope.prices[index].selectNum + 1)) {
                                    scope.prices[index].selectNum = scope.prices[index].marginCount;
                                    scope.pricesChange();
                                    var priceInfo = scope.prices[index];
                                    scope.afterChange({
                                    	"priceInfo":priceInfo
                                    });
                                    var msg = "余票不足！";
                                    scope.showError(index, msg);
                                    return false;
                                }
                                scope.prices[index].selectNum++;
                                scope.pricesChange();
                                //改变之后的回调
                                var priceInfo = scope.prices[index];
                                scope.afterChange({
                                	"priceInfo":priceInfo
                                });
                            };
                            
                            /**
                             * 删除选中的票档
                             */
                            scope.removeSelectPrice = function (index) {
                                scope.prices[index].selectNum = 0;
                                scope.prices[index].isSelect = false;
                                scope.pricesChange();
                                var priceInfo = scope.prices[index];
                                scope.afterChange({
                                	"priceInfo":priceInfo
                                });
                            };
                            
                            
                            /**
                             * 重新加载无座的监听
                             */
                            scope.$on("reload-" + iAttrs.mapName, function (event,data) {
                            	console.log("--------------重新加载无座的监听--------------");
                        		if(scope.prices && scope.prices.length > 0){
                            		for(var i=0;i<scope.prices.length;i++){
                                		var pri = scope.prices[i];
                                		for(var k=0;k<data.priceInfos.length;k++){
                                			var buy = data.priceInfos[k];
                                			if(buy.priceId == pri.priceId){
                                				scope.prices[i].selectNum = buy.priceNum;
                                				scope.prices[i].isSelect = true;
                                				scope.afterChange({
                                                	"priceInfo":scope.prices[i]
                                                });
                                			}
                                		}
                                	}
                            	}
                            	scope.pricesChange();

                                if(data.clearAll){
                                    for(var i=0;i<scope.prices.length;i++){
                                        scope.prices[i].selectNum = 0;
                                        scope.prices[i].isSelect = false;
                                        scope.afterChange({
                                            "priceInfo":scope.prices[i]
                                        });
                                    }
                                }
                            });
                            
                            /**
                             * 清除当前所有
                             */
                            scope.$on("clearAll-" + iAttrs.mapName, function (event, preventCallback) {
                            	for(var i=0;i<scope.prices.length;i++){
                    				scope.prices[i].selectNum = 0;
                    				scope.prices[i].isSelect = false;
                            	}
                            	
                            	if (preventCallback != true) {
                    				scope.afterChange({
                                    	"priceInfo":scope.prices
                                    });
                            	}
                            });
                            
                            /**
                             * 清除其中一个票档
                             */
                            scope.$on("remove-" + iAttrs.mapName, function (event,data) {
                            	for(var i=0;i<scope.prices.length;i++){
                            		if(scope.prices[i].superGoodIds == data.priceInfo.superGoodId){
                            			scope.prices[i].selectNum = 0;
                        				scope.prices[i].isSelect = false;
                        				scope.afterChange({
                                        	"priceInfo":scope.prices[i]
                                        });
                        				break;
                            		}
                            	}
                            });
                            
                            scope.checkMaxTicketNum = function (index) {
                                var count = 0;
                                for (var i = 0; i < scope.prices.length; i++) {
                                    if (scope.prices[i].isSelect && i != index) {
                                        count += parseInt(scope.prices[i].selectNum);
                                    }
                                }
                                return scope.maxTicketNum - count;
                            };
                            scope.showError = function (index, errorMsg) {
                                $("#price" + index).addClass("error");
                                //$("span.not-enough").remove();
                                $("#price" + index).append('<span id="errorMsg' + index + '" class="not-enough">' + errorMsg + '</span>');

                            };
                            scope.clearError = function (index) {
                                //$("#price" + index).removeClass("error");
                                $("li.error").removeClass("error");
                                $("span.not-enough").remove();
                            };
                            scope.editSelectNum = function (value, index) {
                                scope.clearError(index);
                                if (!/^[0-9]*$/.test(value)) {
                                    return;
                                }
                                var maxMore = false;
                                var error = "";
                                var ticketMarginCount = scope.checkMaxTicketNum(index);//余量
                                if (ticketMarginCount < value) {
                                    //余量小于输入数目
                                    value = ticketMarginCount;
                                    maxMore = true;
                                    error = "";
                                    // MaiDialog.error("单笔订单最多" + scope.maxTicketNum + "张票");
                                    //scope.showError(index, "单笔订单最多" + scope.maxTicketNum + "张票");
                                    // return;
                                }

                                if (scope.prices[index].marginCount < value) {
                                    scope.prices[index].selectNum = scope.prices[index].marginCount;
                                    scope.pricesChange();
                                    var priceInfo = scope.prices[index];
                                    scope.afterChange({
                                    	"priceInfo":priceInfo
                                    });
                                    error = error + "余票不足！";
                                    scope.showError(index, error);
                                    return;
                                }


                                if (/^\+?[1-9][0-9]*$/.test(value)) {
                                    if (scope.prices[index].marginCount < value) {
                                        scope.prices[index].selectNum = scope.prices[index].marginCount;
                                        scope.pricesChange();
                                        var priceInfo = scope.prices[index];
                                        scope.afterChange({
                                        	"priceInfo":priceInfo
                                        });
                                        error = error + "余票不足！";
                                        scope.showError(index, error);
                                        return;
                                    }
                                    scope.prices[index].selectNum = value;
                                    scope.pricesChange();
                                    var priceInfo = scope.prices[index];
                                    scope.afterChange({
                                    	"priceInfo":priceInfo
                                    });
                                    var priceInfo = scope.prices[index];
                                    scope.afterChange({
                                    	"priceInfo":priceInfo
                                    });
                                } else {
                                    // MaiDialog.error("必须输入正整数！");
                                    error = error + "必须输入正整数！";
                                    scope.showError(index, error);
                                    scope.prices[index].selectNum = 1;
                                    scope.pricesChange();
                                    var priceInfo = scope.prices[index];
                                    scope.afterChange({
                                    	"priceInfo":priceInfo
                                    });
                                }
                                if (maxMore) {
                                    scope.showError(index, error);
                                }


                            };
                            scope.$on("reload-" + scope.id, function (event, conditionObj) {
                                scope.eventId = conditionObj;
                                scope.allSelectNum = 0;
                                scope.allSelectPrice = 0;
                                //scope.ngModel.length = 0;
                                scope.loadSelectionData();
                            });


                            if (!scope.ngModel) {
                                console.error("ngModel对象为空");
                                return;
                            }
                            if (!iAttrs.maxTicketNum) {
                                scope.maxTicketNum = 200;
                            }

                            if (!iAttrs.eventId) {
                                console.error("selectNoSeat的属性event-id不能为空");
                                return;
                            } else {
                                scope.loadSelectionData();
                            }

                        }
                    }
                },
                link: function (scope, iElement, iAttrs) {
                    scope.type = iAttrs.type;
                }
            };
        }]);
    });